package org.zjx.server.scanner;

import org.reflections.Reflections;
import org.reflections.scanners.Scanners;
import org.reflections.util.ConfigurationBuilder;
import org.zjx.server.annotation.RpcService;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class ServiceScanner {
    private static final Reflections reflections = new Reflections(
            new ConfigurationBuilder()
                    .forPackages("") // 扫描所有包
                    .setScanners(Scanners.TypesAnnotated)
    );

    public static Map<Class<?>, Object> scanServices() {
        Map<Class<?>, Object> services = new HashMap<>();

        // 获取所有带@RpcService注解的类
        Set<Class<?>> serviceClasses = reflections.getTypesAnnotatedWith(RpcService.class);

        for (Class<?> clazz : serviceClasses) {
            RpcService annotation = clazz.getAnnotation(RpcService.class);
            Class<?> serviceInterface = annotation.value();

            try {
                Object serviceInstance = clazz.getDeclaredConstructor().newInstance();
                services.put(serviceInterface, serviceInstance);
            } catch (Exception e) {
                throw new RuntimeException("Failed to instantiate service: " + clazz.getName(), e);
            }
        }

        return services;
    }
}